//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { useState, useMemo, useEffect } from 'react';
import React from 'react';
import s from './index.module.less';
import { useHistory, useLocation } from 'react-router-dom';
import { WORKBENCH_PATH } from '@/utils/constant';
import { useStores } from '@/hooks';
import Card from './components/Card';
import InfoCount from './components/InfoCount';
import { Modal, Popover, Segmented, Space, Tabs } from 'antd';
import { observer } from 'mobx-react';
import { AppstoreOutlined, ExportOutlined, FolderOutlined, InfoCircleOutlined, MoreOutlined, PlusOutlined, WarningOutlined } from '@ant-design/icons';
import Button from '@/components/Button';
import UserAppList from './UserAppList';
import LocalRepoList from './LocalRepoList';
import AddRepoModal from './components/localrepo/AddRepoModal';
import { USER_TYPE_ATOM_GIT, USER_TYPE_GIT_CODE, USER_TYPE_GITEE } from '@/api/user';
import iconAtomgit from '@/assets/allIcon/icon-atomgit.png';
import iconGitee from '@/assets/allIcon/icon-gitee.png';
import iconGitCode from '@/assets/allIcon/icon-gitcode.png';
import AtomGitPanel from './AtomGitPanel';
import { open as shell_open } from '@tauri-apps/api/shell';
import { install_lfs } from "@/api/git_wrap";
import GiteePanel from './GiteePanel';
import GitCodePanel from './GitCodePanel';
import AppStorePanel from './AppStorePanel';
import DebugMinAppModal from '@/components/MinApp/DebugMinAppModal';
import WelcomeInfo from './components/WelcomeInfo';
import MoreTabList from './MoreTabList';
import GitConfigModal from './components/localrepo/GitConfigModal';
import AssistantConfigModal from './components/localrepo/AssistantConfigModal';
import { useTranslation } from "react-i18next";

const Workbench: React.FC = () => {
  const location = useLocation();
  const history = useHistory();

  const { t } = useTranslation();

  const urlParams = new URLSearchParams(location.search);

  const userStore = useStores('userStore');
  const projectStore = useStores('projectStore');
  const orgStore = useStores('orgStore');
  const localRepoStore = useStores("localRepoStore");
  const appStore = useStores("appStore");

  const tab = urlParams.get('tab') ?? (userStore.sessionId == "" && localRepoStore.repoExtList.length == 0 ? "welcome" : "localRepo");
  const subTab = urlParams.get('subTab') ?? "";

  const [showAddRepoModal, setShowAddRepoModal] = useState(false);
  const [showGitConfigModal, setShowGitConfigModal] = useState(false);
  const [showGitLfsConfigModal, setShowGitLfsConfigModal] = useState(false);
  const [showAssistantConfigModal, setShowAssistantConfigModal] = useState(false);

  const [minAppSegValue, setMinAppSegValue] = useState<"myApp" | "appStore">("myApp");
  const [showMinAppDebug, setShowMinAppDebug] = useState(false);


  useMemo(() => {
    projectStore.setCurProjectId('');
    orgStore.setCurOrgId("");
  }, []);

  useEffect(() => {
    if (userStore.sessionId == "" && ["atomGit", "gitCode", "gitee", "userApp", "more"].includes(tab)) {
      history.push(`${WORKBENCH_PATH}?tab=welcome`);
    }
  }, [userStore.sessionId]);

  useEffect(() => {
    setMinAppSegValue("myApp");
  }, [tab]);

  return (
    <div className={s.workbench_wrap}>
      <Card className={s.infoCount_wrap} childStyle={{ height: '100%', overflow: "hidden" }}>
        {!userStore.isResetPassword && <InfoCount />}
      </Card>
      <Tabs activeKey={tab} className={s.my_wrap} type="card"
        onChange={key => {
          let subTab = "";
          if (appStore.vendorCfg?.work_bench.enable_user_memo == true) {
            subTab = "userMemo";
          } else if (appStore.vendorCfg?.work_bench.enable_server_list == true) {
            subTab = "userServer";
          }
          history.push(`${WORKBENCH_PATH}?tab=${key}&subTab=${subTab}`);
        }}
        tabBarStyle={{ marginBottom: "0px" }}
        tabBarExtraContent={
          <div>
            {tab == "userApp" && (
              <Space>
                <Segmented options={[
                  {
                    label: <span style={{ color: minAppSegValue == "myApp" ? "blue" : undefined, fontSize: "16px", fontWeight: 700 }}>{t("text.installed")}</span>,
                    value: "myApp",
                  },
                  {
                    label: <span style={{ color: minAppSegValue == "appStore" ? "blue" : undefined, fontSize: "16px", fontWeight: 700 }}>{t("text.appStore")}</span>,
                    value: "appStore",
                  }
                ]} value={minAppSegValue} onChange={value => setMinAppSegValue(value as "myApp" | "appStore")} />
                <Popover placement="bottom" trigger="click" content={
                  <Space direction="vertical">
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowMinAppDebug(true);
                    }}>{t("text.debugApp")}</Button>
                  </Space>
                }>
                  <MoreOutlined style={{ marginRight: "32px" }} />
                </Popover>
              </Space>
            )}
            {tab == "localRepo" && localRepoStore.checkResult != null && (
              <Space>
                {localRepoStore.checkResult.hasGit == false && (
                  <>
                    <Button type="text" style={{ color: "red", fontWeight: 700, fontSize: "14px" }}
                      onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open("https://git-scm.com/downloads");
                      }}><WarningOutlined />{t("text.installGit")}</Button>
                    <Button type="default" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      localRepoStore.checkGitEnv();
                    }}>{t("text.recheck")}</Button>
                  </>
                )}
                {localRepoStore.checkResult.hasGit && localRepoStore.checkResult.hasConfigGit == false && (
                  <Button type="text" style={{ color: "red", fontWeight: 700, fontSize: "14px" }}
                    onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowGitConfigModal(true);
                    }}><WarningOutlined />{t("text.unConfigGitUser")}</Button>
                )}
                {localRepoStore.checkResult.hasGit && localRepoStore.checkResult.hasConfigGit && localRepoStore.checkResult.hasGitLfs == false && (
                  <>
                    <Button type="text" style={{ color: "red", fontWeight: 700, fontSize: "14px" }}
                      onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open("https://git-lfs.com/");
                      }}><WarningOutlined />{t("text.installGitLfs")}</Button>
                    <Button type="default" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      localRepoStore.checkGitEnv();
                    }}>{t("text.recheck")}</Button>
                  </>
                )}
                {localRepoStore.checkResult.hasGit && localRepoStore.checkResult.hasConfigGit && localRepoStore.checkResult.hasGitLfs && localRepoStore.checkResult.hasConfigGitLfs == false && (
                  <Button type="text" style={{ color: "red", fontWeight: 700, fontSize: "14px" }}
                    onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowGitLfsConfigModal(true);
                    }}><WarningOutlined />t("text.unConfigGitLfs")</Button>
                )}
                {localRepoStore.checkResult.hasGit && (
                  <Button style={{ marginRight: "20px", backgroundColor: localRepoStore.repoExtList.length == 0 ? "orange" : undefined, border: localRepoStore.repoExtList.length == 0 ? "none" : undefined }}
                    onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowAddRepoModal(true);
                    }} icon={<PlusOutlined />}>
                    {t("text.add")}
                  </Button>
                )}
                <Popover trigger="click" placement="bottomLeft" content={
                  <Space direction="vertical">
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowGitConfigModal(true);
                    }}>{t("workbench.localRepo.configGitUser")}</Button>
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowAssistantConfigModal(true);
                    }}>{t("workbench.localRepo.configGitAssistantMode")}</Button>
                  </Space>
                }>
                  <MoreOutlined style={{ marginRight: "32px" }} />
                </Popover>
              </Space>
            )}
            {tab == "atomGit" && (
              <Space>
                <Button type="link" onClick={e => {
                  e.stopPropagation();
                  e.preventDefault();
                  shell_open("https://atomgit.com/project/new");
                }}>
                  <span style={{ fontSize: "14px", fontWeight: 600 }}>
                    创建项目&nbsp;<ExportOutlined />
                  </span>
                </Button>
                <Popover trigger="click" placement="bottom" content={
                  <div style={{ padding: "10px 10px" }}>
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      shell_open("https://docs.atomgit.com");
                    }}>查看帮助&nbsp;<ExportOutlined /></Button>
                  </div>
                }>
                  <MoreOutlined style={{ marginRight: "32px" }} />
                </Popover>
              </Space>
            )}
            {tab == "gitee" && (
              <Space>
                <Button type="link" onClick={e => {
                  e.stopPropagation();
                  e.preventDefault();
                  shell_open("https://gitee.com/projects/new");
                }}>
                  <span style={{ fontSize: "14px", fontWeight: 600 }}>
                    创建项目&nbsp;<ExportOutlined />
                  </span>
                </Button>
                <Popover trigger="click" placement="bottom" content={
                  <div style={{ padding: "10px 10px" }}>
                    <Button type="link" onClick={e => {
                      e.stopPropagation();
                      e.preventDefault();
                      shell_open("https://help.gitee.com/");
                    }}>查看帮助&nbsp;<ExportOutlined /></Button>
                  </div>
                }>
                  <MoreOutlined style={{ marginRight: "32px" }} />
                </Popover>
              </Space>
            )}
          </div>
        }>
        {userStore.sessionId != "" && userStore.userInfo.userType == USER_TYPE_ATOM_GIT && (
          <Tabs.TabPane tab={<h2><img src={iconAtomgit} style={{ width: "14px", marginRight: "10px", marginTop: "-4px" }} />AtomGit</h2>} key="atomGit">
            {tab == "atomGit" && (
              <div className={s.content_wrap}>
                <AtomGitPanel />
              </div>
            )}
          </Tabs.TabPane>
        )}
        {userStore.sessionId != "" && userStore.userInfo.userType == USER_TYPE_GIT_CODE && (
          <Tabs.TabPane tab={<h2><img src={iconGitCode} style={{ width: "14px", marginRight: "10px", marginTop: "-4px" }} />GitCode</h2>} key="gitCode">
            {tab == "gitCode" && (
              <div className={s.content_wrap}>
                <GitCodePanel />
              </div>
            )}
          </Tabs.TabPane>
        )}
        {userStore.sessionId != "" && userStore.userInfo.userType == USER_TYPE_GITEE && (
          <Tabs.TabPane tab={<h2><img src={iconGitee} style={{ width: "14px", marginRight: "10px", marginTop: "-4px" }} />Gitee</h2>} key="gitee">
            {tab == "gitee" && (
              <div className={s.content_wrap}>
                <GiteePanel />
              </div>
            )}
          </Tabs.TabPane>
        )}
        <Tabs.TabPane tab={<h2><FolderOutlined />{t("workbench.main.localRepo")}</h2>} key="localRepo">
          {tab == "localRepo" && (
            <div className={s.content_wrap}>
              <LocalRepoList />
            </div>
          )}
        </Tabs.TabPane>

        {appStore.vendorCfg?.work_bench.enable_minapp == true && (
          <Tabs.TabPane tab={<h2 style={{ color: userStore.sessionId == "" ? "#aaa" : undefined }} title={userStore.sessionId == "" ? "需登录状态" : ""}><AppstoreOutlined />{t("workbench.main.minapp")}</h2>} key="userApp" disabled={userStore.sessionId == ""}>
            {tab == "userApp" && (
              <div className={s.content_wrap}>
                {minAppSegValue == "myApp" && <UserAppList onCount={appCount => {
                  if (appCount == 0) {
                    setMinAppSegValue("appStore");
                  }
                }} />}
                {minAppSegValue == "appStore" && <AppStorePanel />}
              </div>
            )}
          </Tabs.TabPane>
        )}

        {((appStore.vendorCfg?.work_bench.enable_user_memo == true) || (appStore.vendorCfg?.work_bench.enable_server_list == true)) && (
          <Tabs.TabPane tab={<h2 style={{ color: userStore.sessionId == "" ? "#aaa" : undefined }}><MoreOutlined />{t("workbench.main.more")}</h2>} key="more" disabled={userStore.sessionId == ""}>
            {tab == "more" && (
              <MoreTabList subTab={subTab} />
            )}
          </Tabs.TabPane>
        )}

        <Tabs.TabPane tab={<h2><InfoCircleOutlined />{t("workbench.main.wlecome")}</h2>} key="welcome">
          {tab == "welcome" && (
            <div className={s.content_wrap}>
              {appStore.vendorCfg?.layout.welcome_page_url == "" && <WelcomeInfo />}
              {appStore.vendorCfg?.layout.welcome_page_url != "" && <iframe src={appStore.vendorCfg?.layout.welcome_page_url ?? ""} width="100%" height="100%" allow='*' />}
            </div>
          )}
        </Tabs.TabPane>


      </Tabs>
      {showAddRepoModal == true && (
        <AddRepoModal onCancel={() => setShowAddRepoModal(false)} onOk={() => {
          localRepoStore.loadRepoList();
          setShowAddRepoModal(false);
        }} />
      )}
      {showGitConfigModal == true && (
        <GitConfigModal onCancel={() => setShowGitConfigModal(false)} onOk={() => {
          setShowGitConfigModal(false);
          localRepoStore.checkGitEnv();
        }} />
      )}
      {showGitLfsConfigModal == true && (
        <Modal open title="配置GitLfs" mask={false}
          okText="执行"
          onCancel={e => {
            e.stopPropagation();
            e.preventDefault();
            setShowGitLfsConfigModal(false);
          }}
          onOk={e => {
            e.stopPropagation();
            e.preventDefault();
            install_lfs().then(() => {
              setShowGitLfsConfigModal(false);
              localRepoStore.checkGitEnv();
            });
          }}>
          是否执行git lfs install?
        </Modal>
      )}
      {showMinAppDebug == true && (
        <DebugMinAppModal onCancel={() => setShowMinAppDebug(false)} onOk={() => setShowMinAppDebug(false)} />
      )}
      {showAssistantConfigModal == true && (
        <AssistantConfigModal onClose={() => setShowAssistantConfigModal(false)} />
      )}
    </div>
  );
};

export default observer(Workbench);
